package service

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/tycme/gin-chat/util"
	"log"
	"sync"
	"time"
)

var mutex sync.Mutex

func (manager *ClientManager) Start() {
	for {
		log.Println("<---监听管道通信--->")
		select {
		case conn := <-Manager.Register: // 建立连接
			log.Println("注册用户， ,client.UserId=" + conn.UserId + " ,client.Account=" + conn.Account)
			//conn.Lock.Lock()

			if value, ok := Manager.Clients.Load(conn.UserId); ok {
				client := value.(*Client)
				replyMsg := &ReplyMsg{
					UserId:     conn.UserId,
					Code:       30016,
					CreateTime: time.Now().UnixMicro(),
					Content:    "你的账号已经被人登录",
				}
				msg, _ := json.Marshal(replyMsg)
				log.Printf("该用户异地登录，把用户踢出， conn.UserId=" + conn.UserId + "，conn.account=" + conn.Account)
				client.Socket.WriteMessage(websocket.TextMessage, msg)
				_ = client.Socket.Close()
				Manager.Clients.Delete(conn.UserId)
			}
			Manager.Clients.Store(conn.UserId, conn)
			replyMsg := &ReplyMsg{
				UserId:     conn.UserId,
				Code:       200,
				CreateTime: time.Now().UnixMicro(),
				Content:    "已连接至服务器",
			}
			msg, _ := json.Marshal(replyMsg)

			//fmt.Println("conn.SendID=" + conn.SendID + ",")
			err := conn.Socket.WriteMessage(websocket.TextMessage, msg)
			//conn.Lock.Unlock()
			if err != nil {
				fmt.Println("error 发送失败," + err.Error())
			}

		case conn := <-Manager.Unregister: // 断开连接
			log.Printf("网络连接中断， conn.UserId=" + conn.UserId + "，conn.account=" + conn.Account)
			if _, ok := Manager.Clients.Load(conn.UserId); ok {
				replyMsg := &ReplyMsg{
					UserId:     conn.UserId,
					Code:       util.WebsocketEnd,
					CreateTime: time.Now().UnixMicro(),
					Content:    "连接已断开",
				}
				msg, _ := json.Marshal(replyMsg)
				_ = conn.Socket.WriteMessage(websocket.TextMessage, msg)
				log.Println("注销用户 ,client.UserId=" + conn.UserId + " ,client.Account=" + conn.Account)
				//		close(conn.Send)
				//deleteKey := c.UserId
				//if _, ok := Manager.Clients.Load(deleteKey); ok {
				//
				//	Manager.Clients.Delete(deleteKey)
				//}

				_ = conn.Socket.Close()
				Manager.Clients.Delete(conn.UserId)
				//delete(Manager.Clients, conn.Identity)
			}
		//广播信息
		case broadcast := <-Manager.Broadcast:
			message := broadcast.Message
			fmt.Println(message)
			//sendId := broadcast.Client.Identity
			//flag := false // 默认对方不在线
			//for id, conn := range Manager.Clients {
			//	if id != sendId {
			//		continue
			//	}
			//	select {
			//	case conn.Send <- message:
			//		flag = true
			//	default:
			//		close(conn.Send)
			//		delete(Manager.Clients, conn.Identity)
			//	}
			//}
			////id := broadcast.Client.ID
			//if flag {
			//	log.Println("对方在线应答")
			//	replyMsg := &ReplyMsg{
			//		Code:    util.WebsocketOnlineReply,
			//		Content: "对方在线应答",
			//	}
			//	msg, _ := json.Marshal(replyMsg)
			//
			//	_ = broadcast.Client.Socket.WriteMessage(websocket.TextMessage, msg)
			//
			//} else {
			//	log.Println("对方不在线")
			//	replyMsg := ReplyMsg{
			//		Code:    util.WebsocketOfflineReply,
			//		Content: "对方不在线应答",
			//	}
			//	msg, _ := json.Marshal(replyMsg)
			//	_ = broadcast.Client.Socket.WriteMessage(websocket.TextMessage, msg)
			//	//err = InsertMsg(conf.MongoDBName, id, string(message), 0, int64(3*month))
			//	//if err != nil {
			//	//	fmt.Println("InsertOneMsg Err", err)
			//	//}
			//}
		}
	}
}
